using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using usm.SolDev.Common.Config;
using usm.SolDev.DataBase.DataObjects;
using usm.SolDev.DataBase;
using usm.SolDev.DataBase.DataAccess;
using usm.SolDev.Common;
using System.Runtime.Remoting.Messaging;
using usm.SolDev.UI.Sys;

namespace usm.SolDev.UI.User
{
    public partial class UserLoginForm : usm.SolDev.UI.BaseForm
    {

        public UserLoginForm()
        {
            InitializeComponent();
        }

        #region Form event handlers
        /// <summary>
        ///     Save preferences an login to database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            UserLoginConfig userLoginConfig = new UserLoginConfig(txtUser.Text.Trim(), txtPassword.Text);
            userLoginConfig.SaveToFile();
            (new GetUserLoginInfoDelegate(DataProvider.DataBase.GetUserInfoData)).BeginInvoke(userLoginConfig.Login, userLoginConfig.Password, new AsyncCallback(GetUserLoginInfoCallBack),  null);
            base.StartWaiting();
        }


        /// <summary>
        ///     On text changed for login and password
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTextChanged(object sender, EventArgs e)
        {
            btnLogin.Enabled = (txtUser.Text.Trim() != "") && (txtPassword.Text != "");
        }

        /// <summary>
        ///     Invoke settings form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SystemSettingsForm systemSettings = new SystemSettingsForm();
            systemSettings.ShowDialog();
        }

        /// <summary>
        ///     Read last user entered values and assign them to visual controls
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserLogin_Load(object sender, EventArgs e)
        {
            UserLoginConfig userLoginConfig = new UserLoginConfig();
            try
            {
                userLoginConfig = (UserLoginConfig)userLoginConfig.LoadFromFile(userLoginConfig);
            } catch (SolDev.Common.SolDevException /*ex*/)
            {
                userLoginConfig.SaveToFile(userLoginConfig);
            }

            txtUser.Text = userLoginConfig.Login;
            txtPassword.Text = "";
        }

        #endregion

        #region Database processing delegates
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private delegate UserInfoData GetUserLoginInfoDelegate(string login, string password);
        private void GetUserLoginInfoCallBack(IAsyncResult ar)
        {
            try
            {
                UserInfoData userInfoData = ((GetUserLoginInfoDelegate)((AsyncResult)ar).AsyncDelegate).EndInvoke(ar);

                if (!IsDisposed && IsHandleCreated)
                {
                    BeginInvoke(new AfterOperationCompletedDelegate(AfterOperationCompleted), new object[] { true, userInfoData });
                }
            }
            catch (Exception ex)
            {
                BeginInvoke(new AfterOperationCompletedDelegate(AfterOperationCompleted), new object[] { false, null });
                new SolDevException("Cannot complete login process", ex);
            }
        }
    
        /// <summary>
        ///     Finalize login information and keep the user's related data to
        /// work session instance.
        /// </summary>
        /// <param name="success"></param>
        /// <param name="userInfoData"></param>
        private delegate void AfterOperationCompletedDelegate (bool success, UserInfoData userInfoData);
        private void AfterOperationCompleted(bool success, UserInfoData userInfoData)
        {
            base.EndWaiting();

            if (success == true)
            {
                 if( userInfoData != null)
                 {
                     WorksessionData.UserInfo = userInfoData;
                     DialogResult = DialogResult.OK;
                 }
                 else
                 {
                     new SolDevException("Could not login to system. Please check the user name and password");
                 }
            }
        }
        #endregion
    }
}

